﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.Data;
using Jumpton.SFA.Entity;
using Jumpton.SFA.Server.Entity;

namespace BusinessRule.Device
{
    public class DeviceControlManager : BusinessLogic
    {
        /// <summary>
        /// 新增设备
        /// </summary>
        /// <returns></returns>
        private bool InsertDeviceControl(DeviceControl dev) 
        {
            bool flag = false;
            if (dev!=null)
            {
                try
                {
                    dev.Save();
                    flag = true;
                }
                catch (Exception)
                {
                    flag = false;
                }
            }
            return flag;
        }

        /// <summary>
        /// 检测用户和设备是否绑定
        /// </summary>
        /// <returns></returns>
        public string CheckUserDevice(UserDeviceBound udb, DeviceControl dev)
        {
            if(!CheckDeviceControl(dev)){
                InsertDeviceControl(dev);
            }
            string sSql = string.Format(@"select count(*) from UserDeviceBound wehre userid='{0}' 
                                and DeviceID = '{1}'",udb.UserID,udb.DeviceID);
            int k = (int)SqlData.ExecuteScalar(sSql);
            if (k>0)
            {
                return "0";
            }
            return "1";
        }


        /// <summary>
        /// 用户绑定设备
        /// </summary>
        /// <param name="udb"></param>
        /// <returns></returns>
        private bool SaveUserDeviceBound(UserDeviceBound udb)
        {
            bool flag = false;
            if (udb != null)
            {
                try
                {
                    udb.Save();
                    flag = true;
                }
                catch (Exception)
                {
                    flag = false;
                }
            }
            return flag;
        }


        /// <summary>
        /// 检测设备是否存在
        /// </summary>
        /// <param name="dev"></param>
        /// <returns>存在返回true,反之返回false</returns>
        private bool CheckDeviceControl(DeviceControl dev)
        {
            string sSql = string.Format(@"select count(*) form DeviceControl where DeviceId = '{0}'",dev.DeviceID);
            int k = (int)SqlData.ExecuteScalar(sSql);
            if (k>0)
            {
                return true;
            }
            return false;
        }


    }
}
